timeTable={}
timeIndex=0
function setTimeout(func,time)
    tmr.alarm(timeIndex,time,0,func)
    if timeIndex < 6 then
        timeIndex=timeIndex+1
    else
        timeIndex=0
    end
end

function setInterval(func,time)
    tmr.alarm(timeIndex,time,1,func)
    if timeIndex < 6 then
        timeIndex=timeIndex+1
    else
        timeIndex=0
    end
end
function call(name)
    file.remove("user.lua")
    file.open("user.lua","w+")
    file.writeline(name)
    file.close()
    dofile("user.lua")
end

function debug(d)
    if DEBUG then
        print(tmr.time(),type(d),d)
    end
end

--链接wifi
function wifi_connect(ssid,pwd)
    wifi_config(ssid,pwd)
    --debug("Connect To "..ssid..":"..pwd)
    wifi.sta.connect()
end
--配置wifi
function wifi_config(ssid,pwd)
    station_cfg={}
    station_cfg.ssid=ssid
    station_cfg.pwd=pwd
    station_cfg.save=true
    station_cfg.auto=true
    wifi.sta.config(station_cfg)
end
--配置ap模式
function wifi_ap_config(ssid,pwd)
    cfg={
        ssid=ssid,
        pwd=pwd,
        auth=wifi.WPA2_PSK,
        max=1,
        save=false
    }
    wifi.ap.config(cfg)
    wifi.setmode(wifi.SOFTAP)
end
--开始智能配网
function wifi_start_smart()
    wifi.setmode(wifi.STATION)
    wifi.startsmart(0,
        function(ssid, password)
            debug("SSID: "..ssid," PWD: "..password)            
            wifi.sta.autoconnect(1)
        end
    )
end
--清除配置文件
function wifi_clean()
    wifi.sta.clearconfig();
end
function wifi_reset()

end
-- Print AP list that is easier to read
function wifi_get_ap(t) -- (SSID : Authmode, RSSI, BSSID, Channel)
    print("\n"..string.format("%32s","SSID").."\tBSSID\t\t\t\t  RSSI\t\tAUTHMODE\tCHANNEL")
    for ssid,v in pairs(t) do
        local authmode, rssi, bssid, channel = string.match(v, "([^,]+),([^,]+),([^,]+),([^,]+)")
        print(string.format("%32s",ssid).."\t"..bssid.."\t  "..rssi.."\t\t"..authmode.."\t\t\t"..channel)
        if ssid == Status.Wifi.SSID then
            wifi_connect(Status.Wifi.SSID,Status.Wifi.PWD);
        end
    end
end

ws = nil;
-- 初始化状态为1
ws_status=nil
ws_cb={}
function ws_init()
    debug("Start WebSocket")
    ws = websocket.createClient()
    ws:config({headers={['User-Agent']='Castle'}})
    ws:on("connection",function(ws)
        ws_status=true
        ws_login()
        if ws_connect then
            pcall(ws_connect_cb,{})
        end
    end)
    ws:on("receive",function(_,msg,opcode)
        debug(msg)
        if ws_receive_cb then
            pcall(ws_receive_cb,{msg})
        end
        local ok,t = pcall(sjson.decode,msg)
        if ok and t then
            if "userdata" == type(t.i) then
            else
                if "nil" == type(ws_cb[ t.t .. t.i ]) then
                    if ws_not_regist_cb then
                        pcall(ws_not_regist_cb,t)
                    end
                else
                    if t.e and string.len(t.e) > 0 then
-- 服务器响应失败回调
                        pcall(ws_cb[t.t .. t.i].e,{t.e,t})
                    else
-- 服务器响应成功回调
                        pcall(ws_cb[t.t .. t.i].s,{t.d,t})
                    end
                end             
            end
        else
            if ws_decode_error_cb then
                pcall(ws_decode_error_cb,{msg})
            end            
        end
    end)
    ws:on("close",function(_,status)
        debug("Closed:",status)
        ws=nil
        setTimeout(ws_init,3000)
    end)
    ws:connect(ws_url)
end


ws_send = function (cmd,content,success,error)
    local t = tmr.now();
    local obj={i=cmd,t=t,d=content}
    ok, json = pcall(sjson.encode, obj)
    if ok then
        ws_cb[t .. cmd]={s=success,e=error}
        debug(json)
        ws:send(json)
    else
        if ws_send_cb then
            pcall(ws_send_cb,{cmd,content})
        end
    end    
end

ws_login = function()
    ws_send("login",{wifi=wifi.sta.getconfig(),mac=wifi.sta.getmac(),info=node.chipid()},function()
        debug("Success Login")
    end,ws_err)
end
ws_exec=function()

end
ws_err=function(err,t)
    debug("Err: " .. err)
end
ws_log=function(msg)
    ws_send("log",{m=msg,t=tmr.time()})
end

DEBUG=true

ws_url='ws://js.s.tansuyun.cn:17420'

Status = {Wifi={
    SSID="",PWD=""
}};
--wifi获取ip成功回调
function on_wifi_got_ip(t)
    pcall(ready,{})
end
--wifi sta模式0
function on_wifi_sta_connected(t)
end
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED,on_wifi_sta_connected)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP,on_wifi_got_ip)

function init()
    local SSID,PWD = wifi.sta.getconfig()
    if string.len(SSID) > 0 then
        Status.Wifi.SSID = SSID;
        Status.Wifi.PWD = PWD;
        wifi.sta.getap(wifi_get_ap);
    else
        print("Start Smart Config")
        wifi.sta.clearconfig()
        wifi_start_smart()
    end
end
init()
